package com.rdxer.service;

import com.rdxer.api.para.PaperAddQuestionPara;
import com.rdxer.core.ex.ObjectEx;
import com.rdxer.core.exception.exceptions.BaseException;
import com.rdxer.core.security.AppUserDetails;
import com.rdxer.core.utils.IdWorker;
import com.rdxer.dataview.PaperQuestionDV;
import com.rdxer.model.*;
import com.rdxer.repository.PaperRepository;
import lombok.Data;
import lombok.Getter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Department 服务层
 */
@Service
@Data
@Getter
public class PaperService implements CRUDPageServiceInterface<Paper, String> {


    @Autowired
    private PaperRepository repository;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private QuestionOptionService optionService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private PaperQuestionRelationService paperQuestionRelationService;
    @Autowired
    private AnswerSheetService answerSheetService;

    public List<AnswerSheet> findAllAnswerSheet(String id) {
        return answerSheetService.findAllByPaper(id);
    }


    public List<PaperQuestionDV> findAllQuestion(String id) {
        return paperQuestionRelationService.findQuestionByPaperId(id);
    }

    public void addPaperQuestion(String id, PaperAddQuestionPara paperAddQuestionPara) {
        List<PaperQuestionDV> allQuestion = findAllQuestion(id);
        if (paperAddQuestionPara.getQuestionOptions() == null && paperAddQuestionPara.getId() != null){
            List<QuestionOption> allByQuestionId = optionService.findAllByQuestionId(paperAddQuestionPara.getId());
            paperAddQuestionPara.setQuestionOptions(allByQuestionId);
        }
        paperAddQuestionPara.setId(null);
        ObjectEx.getByReturn(() -> AppUserDetails.getCurrent().account.getId(), v -> {
            paperAddQuestionPara.setUserId(v);
        });
        paperAddQuestionPara.setIsTemplate(false);
        Question newQuestion = new Question();
        BeanUtils.copyProperties(paperAddQuestionPara,newQuestion);
        newQuestion = questionService.add(newQuestion);
        PaperQuestionRelation build = PaperQuestionRelation.builder()
                .idx(allQuestion.size() + 1)
                .paperId(id)
                .questionId(newQuestion.getId())
                .build();
        PaperQuestionRelation add1 = paperQuestionRelationService.add(build);
        for (QuestionOption option : paperAddQuestionPara.getQuestionOptions()) {
            QuestionOption questionOption = new QuestionOption();
            questionOption.setQuestionId(newQuestion.getId());
            questionOption.setIdx(option.getIdx());
            questionOption.setContent(option.getContent());
            questionOption.setCorrect(option.getCorrect());
            questionOption.setRemark(option.getRemark());
            optionService.add(questionOption);
        }
    }

    public void moveQuestion(String id, Question question, int idx) {

        List<PaperQuestionDV> allQuestion = findAllQuestion(id);
        boolean flag = false;
        PaperQuestionDV paperQuestiDV = null;
        for (PaperQuestionDV paperQuesti : allQuestion) {
            if (paperQuesti.getQuestionId().equals(question.getId())) {
                flag = true;
                paperQuestiDV = paperQuesti;
                break;
            }
        }
        if (!flag) {
            throw BaseException.ofBadRequest("访问错误1");
        }

        if (idx < 0 || idx >= allQuestion.size()) {
            throw BaseException.ofBadRequest("访问错误2");
        }


        if (paperQuestiDV.getIdx() == idx) {
            return;
        }

        allQuestion.sort((v1, v2) -> v1.getIdx() - v2.getIdx());

        int orgIndex = allQuestion.indexOf(question);
        int targetIndex = idx - 1;

        allQuestion.remove(orgIndex);

        if (targetIndex > orgIndex) {
            targetIndex -= 1;
        }

        allQuestion.add(targetIndex,paperQuestiDV);


        for (int i = 0; i < allQuestion.size(); i++) {
            PaperQuestionDV dv = allQuestion.get(i);
            paperQuestionRelationService.upIndex(dv.getId(),i+1);
        }
    }

    public void questionMoveToIndex(String relationId, int idx) {
        paperQuestionRelationService.questionMoveToIndex(relationId,idx);
    }


    public void addPaperQuestion2(String id, PaperAddQuestionPara paperAddQuestionPara) {

        List<PaperQuestionDV> allQuestion = findAllQuestion(id);


        if (paperAddQuestionPara.getQuestionOptions() == null && paperAddQuestionPara.getId() != null){
            List<QuestionOption> allByQuestionId = optionService.findAllByQuestionId(paperAddQuestionPara.getId());
            paperAddQuestionPara.setQuestionOptions(allByQuestionId);
        }

        paperAddQuestionPara.setId(null);
        ObjectEx.getByReturn(() -> AppUserDetails.getCurrent().account.getId(), v -> {
            paperAddQuestionPara.setUserId(v);
        });

        Question newQuestion = new Question();
        BeanUtils.copyProperties(paperAddQuestionPara,newQuestion);
        newQuestion = questionService.add(newQuestion);

        PaperQuestionRelation build = PaperQuestionRelation.builder()
                .idx(allQuestion.size() + 1)
                .paperId(id)
                .questionId(newQuestion.getId())
                .build();

        PaperQuestionRelation add1 = paperQuestionRelationService.add(build);


        for (QuestionOption option : paperAddQuestionPara.getQuestionOptions()) {

            QuestionOption questionOption = new QuestionOption();

            questionOption.setQuestionId(newQuestion.getId());
            questionOption.setIdx(option.getIdx());
            questionOption.setContent(option.getContent());
            questionOption.setCorrect(option.getCorrect());
            questionOption.setRemark(option.getRemark());

            optionService.add(questionOption);
        }

    }

    public List<Paper> findAllByCourseId(String courseId) {
        List<Paper> allByCourseId = repository
                .findAllByCourseIdAndAndState(courseId,Paper.State.working.name());
        return allByCourseId;
    }

    public void deletePaperQuestion(String pqRelationId) {
        paperQuestionRelationService.removeRelation(pqRelationId);
    }
}
